import axios from 'axios'
import { Message, Loading} from 'element-ui'

//加载信息
let loding =null

function startLoading () {
  return loding = Loading.service({
    lock: true,
    text: '加载中...',
    background: "rgba(0, 0, 0, 0.7)"
  })
}
//关闭加载信息
function endLoading () {
  loding.close()
}

//注册全部地址
const baseURL = process.env.VUE_APP_API_URL

// const version = '/api'
//创建axios实例
const instance = axios.create({
  baseURL: baseURL,
  timeout: 180000,
  
})

//请求拦截器
instance.interceptors.request.use(
  function (config) {
        // 加载
        startLoading();
        // config.headers['Accept'] = 'text/csv'
        //配置全局token
        config.headers.token = window.localStorage.getItem('token')
        // console.log('请求头',config.headers)
        if(config.url == '/login/do'){
          config.headers.Captcha = window.localStorage.getItem('captcha')
          config.headers.Yzm_Session = window.localStorage.getItem('yzm_session')
        }
        config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        // config.responseType = 'blob'
        // config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        // config.url = (/http(s?):\/\//.test(config.url) ? '' : '/admin') + config.url
        if(config.method.toLowerCase() === 'get'){
          // 增加时间戳 避免GET请求的时候IE缓存
          const timestamp = new Date().getTime()
          config.url += config.url.indexOf('?') !== -1 ? `&_=${timestamp}` : `?_=${timestamp}`
       }
       return config
  },
  function (error) {
    // console.log('error',error)
    return Promise.reject(error);
  }
 )

//响应拦截器

instance.interceptors.response.use(
  function (response) {
    endLoading();
    // console.log('响应',response)
    let blob = new Blob([response.data], {type: 'application/vnd.ms-excel;charset=utf-8'});
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = '导出文件.xls'; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  },function (error) {
    // 错误提醒
    endLoading();
    Message.error('请求超时')
    return Promise.reject(error);
  })

  export default instance



export const baseUrl = baseURL